package com.bwie.shop.handler;

import com.bwie.common.result.Result;
import com.bwie.shop.exception.ShopException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理
 *
 * @author <a href="mailto:3364114353@qq.com">liuwenliang</a>
 * @version 1.0
 * @description: 全局异常处理
 * @date 2025/9/9 10:13
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 登录模块异常处理
     * @param loginException
     * @return 异常信息
     */
    @ExceptionHandler(ShopException.class)
    public Result loginException (ShopException loginException) {
        //打印
        log.error("登录模块异常信息：{}",loginException.getMessage());
        //返回
        return Result.error(loginException.getCode(), loginException.getMessage());
    }


    /**
     * 全局异常处理
     * @param manve
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException (MethodArgumentNotValidException manve) {
        //获取返回结果
        BindingResult bindingResult = manve.getBindingResult();
        //获取所有异常信息
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuffer stringBuffer = new StringBuffer();
        //遍历
        allErrors.forEach(error -> {
            String defaultMessage = error.getDefaultMessage();
            //拼接
            stringBuffer.append(defaultMessage).append("");
            //打印
            log.error("异常信息：{}",defaultMessage);
        });
        return Result.error(stringBuffer.toString());
    }
}
